package com.yiren.manager.ctrl.department;

import java.beans.IntrospectionException;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.yiren.core.exception.MyException;
import com.yiren.core.exception.SwallowException;
import com.yiren.core.repository.utils.QueryResult;
import com.yiren.core.utils.FileUtil;
import com.yiren.core.utils.HTTPResult;
import com.yiren.core.utils.JsonMapperTool;
import com.yiren.core.utils.PropertyConfigurer;
import com.yiren.core.utils.UUIDGenerator;
import com.yiren.entity.YrCaregiver;
import com.yiren.entity.YrCaregiverSendOrdersStandard;
import com.yiren.entity.YrCgIndiServiceSendOrder;
import com.yiren.entity.YrCgSendOrder;
import com.yiren.entity.YrElderBeHospital;
import com.yiren.entity.YrSubjectRoom;
import com.yiren.manager.ctrl.GenericController;
import com.yiren.manager.form.department.YrCaregiverForm;
import com.yiren.manager.form.department.YrCgSendOrderForm;
import com.yiren.manager.form.elder.YrElderBeHospitalForm;
import com.yiren.manager.form.pension.YrCaregiverSendOrdersStandardForm;
import com.yiren.manager.service.iface.department.YrCaregiverService;
import com.yiren.manager.service.iface.department.YrCgIndiServiceSendOrderService;
import com.yiren.manager.service.iface.department.YrCgSendOrderService;
import com.yiren.manager.service.iface.department.YrSubjectRoomService;
import com.yiren.manager.service.iface.elder.YrElderBeHospitalService;
import com.yiren.manager.service.iface.pension.YrCaregiverSendOrdersStandardService;
import com.yiren.manager.utils.ObjectUtils;

@RequestMapping("caregiver")
@Controller
public class YrCaregiverController extends GenericController<YrCaregiverForm, YrCaregiver> {

	@Autowired
	private YrCaregiverService selfService;

	@Autowired
	private YrCgSendOrderService cgSendOrderService;

	@Autowired
	private YrElderBeHospitalService elderBeHospitalService;
	
	@Autowired
	private YrSubjectRoomService subjectRoomService;
	
	@Autowired
	private YrCgIndiServiceSendOrderService cgIndiServiceSendOrderService;
	
	@Autowired
	private YrCaregiverSendOrdersStandardService caregiverSendOrdersStandardService;

	// 保存实体
	@RequestMapping("/save")
	@ResponseBody
	public HTTPResult<YrCaregiverForm> save(String data) throws SwallowException, MyException, InstantiationException,
			IllegalAccessException, IllegalArgumentException, InvocationTargetException, IntrospectionException {
		HTTPResult<YrCaregiverForm> result = new HTTPResult<YrCaregiverForm>();

		System.out.println(data.toString());
		JsonMapperTool tool = new JsonMapperTool(data);
		YrCaregiverForm form = tool.mapper("caregiver", YrCaregiverForm.class);

		if (null == form) {
			throwExp("param.error");
		}
		if (null == form.getCaregiverId() || form.getCaregiverId().isEmpty()) {
			String sqlWhere = "name=?1 AND card_id=?2";
			QueryResult<YrCaregiver> qrCaregiver = selfService.find(YrCaregiver.class, sqlWhere, new Object[]{form.getName(),form.getCardId()});
			if(qrCaregiver.getTotalRecord()>0){
				throwExp("该护理员已存在，请勿重复添加");
			}
			form.setCaregiverId(UUIDGenerator.getUUID());
			form.setCreateTime(new Date());
			form.setExistStatus(0);
		}
		form.setUpdateTime(new Date());
		YrCaregiver caregiver = selfService.findOne(form.getCaregiverId());
		if(null!=caregiver){
			if(form.getStatus()==1 || form.getCaregiverSendOrdersStandardId()!=caregiver.getCaregiverSendOrdersStandardId() ){
				String sqlWhere = "caregiver_id=?1 AND status= 0";
				QueryResult<YrCgSendOrder> qrCgSendOrder = cgSendOrderService.find(YrCgSendOrder.class, sqlWhere, new Object[]{caregiver.getCaregiverId()});
				if(qrCgSendOrder.getTotalRecord()>0){
					throwExp("该护理员尚有未结束的派单，请先结束");
				}
				QueryResult<YrCgIndiServiceSendOrder> qrCgIndiServiceSendOrder = cgIndiServiceSendOrderService.find(YrCgIndiServiceSendOrder.class, sqlWhere, new Object[]{caregiver.getCaregiverId()});
				if(qrCgIndiServiceSendOrder.getTotalRecord()>0){
					throwExp("该护理员尚有未结束的个性服务，请先结束");
				}
			}
		}
		if (null != form.getImgBase64() && !form.getImgBase64().isEmpty()) {
			YrCaregiver entity = selfService.findOne(form.getCaregiverId());
			if (entity != null) {
				FileUtil.deleteFile(String.valueOf(PropertyConfigurer.getContextProperty("yiren.img.save.url"))
						+ entity.getPhotoUrl());
			}
			form.setPhotoUrl(FileUtil.saveBase64(form.getImgBase64(),
					String.valueOf(PropertyConfigurer.getContextProperty("yiren.img.save.url"))));
		}
		YrCaregiver entity = ObjectUtils.objectToObject(form, YrCaregiver.class);

		System.out.println("===="+entity.getCaregiverSendOrdersStandardId());
		selfService.save(entity);

		return result;
	}

//	@RequestMapping("updateStatus")
//	@ResponseBody
//	public HTTPResult<YrCaregiver> updateStatus(Integer status, String id) throws MyException {
//		HTTPResult<YrCaregiver> result = new HTTPResult<YrCaregiver>();
//		YrCaregiver caregiver = selfService.findOne(id);
//		if (null == caregiver) {
//			throwExp("该护理员不存在");
//		}
//		if(status==1){//如果更改的状态是离职
//			String sqlWhere = "caregiver_id=?1 AND status= 0";
//			QueryResult<YrCgSendOrder> qrCgSendOrder = cgSendOrderService.find(YrCgSendOrder.class, sqlWhere, new Object[]{id});
//			if(qrCgSendOrder.getTotalRecord()>0){
//				throwExp("该护理员尚有未结束的派单，请先结束");
//			}
//			QueryResult<YrCgIndiServiceSendOrder> qrCgIndiServiceSendOrder = cgIndiServiceSendOrderService.find(YrCgIndiServiceSendOrder.class, sqlWhere, new Object[]{id});
//			if(qrCgIndiServiceSendOrder.getTotalRecord()>0){
//				throwExp("该护理员尚有未结束的个性服务，请先结束");
//			}
//		}
//	
//		caregiver.setStatus(status);
//		selfService.save(caregiver);
//		return result;
//	}

	@RequestMapping("findAll")
	@ResponseBody
	public HTTPResult<YrCaregiverForm> find() throws Exception {
		HTTPResult<YrCaregiverForm> result = new HTTPResult<YrCaregiverForm>();

		String sqlWhere = "exist_status=0";
		QueryResult<YrCaregiver> qr = selfService.find(YrCaregiver.class, sqlWhere, new Object[] {});
		List<YrCaregiver> entityList = qr.getResultList();

		List<YrCaregiverForm> formList = new ArrayList<YrCaregiverForm>();
		for (YrCaregiver entity : entityList) {
			YrCaregiverForm form = ObjectUtils.objectToObject(entity, YrCaregiverForm.class);
			sqlWhere = "caregiver_id=?1";
			QueryResult<YrCgSendOrder> qrCgSendOrder = cgSendOrderService.find(YrCgSendOrder.class, sqlWhere,
					new Object[] { form.getCaregiverId() });
			if (qrCgSendOrder.getTotalRecord() > 0) {
				List<YrCgSendOrderForm> cgSendOrderForms = new ArrayList<YrCgSendOrderForm>();
				for (YrCgSendOrder cgSendOrder : qrCgSendOrder.getResultList()) {
					String elderId = cgSendOrder.getElderId();
					YrCgSendOrderForm cgSendOrderForm = ObjectUtils.objectToObject(cgSendOrder,
							YrCgSendOrderForm.class);
					sqlWhere = "elderId=?1 AND be_status<>2";
					QueryResult<YrElderBeHospital> qrElderBeHospital = elderBeHospitalService
							.find(YrElderBeHospital.class, sqlWhere, new Object[] { elderId });
					if (qrElderBeHospital.getTotalRecord() > 0) {
						YrElderBeHospital elderBeHospital = qrElderBeHospital.getResultList().get(0);
						cgSendOrderForm.setElderBeHospitalForm(ObjectUtils.objectToObject(elderBeHospital, YrElderBeHospitalForm.class));
					}
					cgSendOrderForms.add(cgSendOrderForm);
				}
				// 设置头像路径
				// if(!StringUtil.isEmpty(form.getPhotoUrl())){
				// form.setPhotoUrl(String.valueOf(PropertyConfigurer.getContextProperty("yiren.img.save.url")+form.getPhotoUrl()));
				// }
				if(form.getSubjectRoomId()!=null){
					YrSubjectRoom subjectRoom = subjectRoomService.findOne(form.getSubjectRoomId());
					if(subjectRoom!=null){
						form.setSubjectRoomName(subjectRoom.getRoomName());
					}
				}
				YrCaregiverSendOrdersStandard caregiverSendOrdersStandard = caregiverSendOrdersStandardService.findOne(form.getCaregiverSendOrdersStandardId());
				if(null!=caregiverSendOrdersStandard){
					YrCaregiverSendOrdersStandardForm sendOrdersStandardForm = ObjectUtils.objectToObject(caregiverSendOrdersStandard, YrCaregiverSendOrdersStandardForm.class);
					form.setCaregiverSendOrdersStandardForm(sendOrdersStandardForm);
				}
				
			}
			formList.add(form);
		}

		result.setData(formList);
		return result;
	}

	@RequestMapping("find")
	@ResponseBody
	public HTTPResult<YrCaregiverForm> find(String searchVal) throws Exception{
		HTTPResult<YrCaregiverForm> result = new HTTPResult<YrCaregiverForm>();
		String sqlWhere = "name=?1 OR card_id=?2";
		
		if(null==searchVal){
			throwExp("参数有误");
		}
		
		QueryResult<YrCaregiver> qr = selfService.find(YrCaregiver.class, sqlWhere, new Object[]{searchVal,searchVal});
		if(qr.getTotalRecord()==0){
			throwExp("查询不到相关的护理员信息");
		}
		YrCaregiver entity = qr.getResultList().get(0);
		YrCaregiverForm form = ObjectUtils.objectToObject(entity,YrCaregiverForm.class);
		sqlWhere = "caregiver_id=?1";
		QueryResult<YrCgSendOrder> qrCgSendOrder = cgSendOrderService.find(YrCgSendOrder.class, sqlWhere,
				new Object[] { form.getCaregiverId() });
		List<YrCgSendOrderForm> cgSendOrderForms = new ArrayList<YrCgSendOrderForm>();
		if (qrCgSendOrder.getTotalRecord() > 0) {
			for (YrCgSendOrder cgSendOrder : qrCgSendOrder.getResultList()) {
				String elderId = cgSendOrder.getElderId();
				YrCgSendOrderForm cgSendOrderForm = ObjectUtils.objectToObject(cgSendOrder,
						YrCgSendOrderForm.class);
				sqlWhere = "elder_id=?1 AND be_status<>2";
				QueryResult<YrElderBeHospital> qrElderBeHospital = elderBeHospitalService
						.find(YrElderBeHospital.class, sqlWhere, new Object[] { elderId });
				if (qrElderBeHospital.getTotalRecord() > 0) {
					YrElderBeHospital elderBeHospital = qrElderBeHospital.getResultList().get(0);
					cgSendOrderForm.setElderBeHospitalForm(ObjectUtils.objectToObject(elderBeHospital, YrElderBeHospitalForm.class));
				}
				cgSendOrderForms.add(cgSendOrderForm);
			}
			form.setCgSendOrderForms(cgSendOrderForms);
			if(form.getSubjectRoomId()!=null){
				YrSubjectRoom subjectRoom = subjectRoomService.findOne(form.getSubjectRoomId());
				if(subjectRoom!=null){
					form.setSubjectRoomName(subjectRoom.getRoomName());
				}
			}
			YrCaregiverSendOrdersStandard caregiverSendOrdersStandard = caregiverSendOrdersStandardService.findOne(form.getCaregiverSendOrdersStandardId());
			if(null!=caregiverSendOrdersStandard){
				YrCaregiverSendOrdersStandardForm sendOrdersStandardForm = ObjectUtils.objectToObject(caregiverSendOrdersStandard, YrCaregiverSendOrdersStandardForm.class);
				form.setCaregiverSendOrdersStandardForm(sendOrdersStandardForm);
			}
		}
		List<YrCaregiverForm> formList = new ArrayList<YrCaregiverForm>();
		formList.add(form);
		result.setData(formList);
		return result;
	}

//	@RequestMapping("updateBetch")
//	@ResponseBody
//	public HTTPResult<YrCaregiverForm> updateBetch(String data) throws SwallowException, MyException {
//		HTTPResult<YrCaregiverForm> result = new HTTPResult<YrCaregiverForm>();
//		JsonMapperTool tool = new JsonMapperTool(data);
//		List<YrCaregiver> form = tool.mapper("caregiverList", new TypeReference<ArrayList<YrCaregiver>>() {
//		});
//
//		this.selfService.updateBetch(form);
//		return result;
//	}

	@RequestMapping("findBySubjectRoomId")
	@ResponseBody
	public HTTPResult<YrCaregiverForm> findBySubjectRoomId(String subjectRoomId) throws Exception {
		HTTPResult<YrCaregiverForm> result = new HTTPResult<YrCaregiverForm>();
		String sqlWhere = "status=0 AND subject_room_id=?1";
		QueryResult<YrCaregiver> qr = selfService.find(YrCaregiver.class, sqlWhere, new Object[] { subjectRoomId });
		List<YrCaregiverForm> formList = new ArrayList<YrCaregiverForm>();
		for (YrCaregiver entity : qr.getResultList()) {
			YrCaregiverForm form = toForm(entity);
			// 设置头像路径
			// if(!StringUtil.isEmpty(form.getPhotoUrl())){
			// form.setPhotoUrl(String.valueOf(PropertyConfigurer.getContextProperty("yiren.img.save.url")+form.getPhotoUrl()));
			// }
			if(form.getSubjectRoomId()!=null){
				YrSubjectRoom subjectRoom = subjectRoomService.findOne(form.getSubjectRoomId());
				if(subjectRoom!=null){
					form.setSubjectRoomName(subjectRoom.getRoomName());
				}
			}
			if(form.getCaregiverSendOrdersStandardId()!=null){
				YrCaregiverSendOrdersStandard caregiverSendOrdersStandard = caregiverSendOrdersStandardService.findOne(form.getCaregiverSendOrdersStandardId());
				if(null!=caregiverSendOrdersStandard){
					YrCaregiverSendOrdersStandardForm sendOrdersStandardForm = ObjectUtils.objectToObject(caregiverSendOrdersStandard, YrCaregiverSendOrdersStandardForm.class);
					form.setCaregiverSendOrdersStandardForm(sendOrdersStandardForm);
				}
			}
			formList.add(form);
		}
		result.setData(formList);
		return result;
	}

//	@RequestMapping("deleteBatch")
//	@ResponseBody
//	public HTTPResult<YrCaregiverForm> deleteBatch(String data) throws MyException, SwallowException {
//		HTTPResult<YrCaregiverForm> result = new HTTPResult<YrCaregiverForm>();
//		JsonMapperTool tool = new JsonMapperTool(data);
//		String[] ids = tool.mapper("ids", String[].class);
//		if (null == ids) {
//			throwExp("param.error");
//		}
//		for (String id : ids) {
//			YrCaregiver caregiver = selfService.findOne(id);
//			if (null != caregiver) {
//				caregiver.setExistStatus(1);
//				selfService.save(caregiver);
//			}
//		}
//		return result;
//	}

	@Override
	public YrCaregiverForm toForm(YrCaregiver e) throws Exception {
		YrCaregiverForm form = ObjectUtils.objectToObject(e, YrCaregiverForm.class);
		return form;
	}

	@Override
	public YrCaregiver toEntity(YrCaregiverForm f) throws Exception {
		// TODO Auto-generated method stub
		return null;
	}

}
